package com.xyy.ec.pop.erp.hx.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xyy.ec.pop.erp.hx.config.HXTaskConfig;
import com.xyy.ec.pop.erp.hx.enums.TaskEnum;
import com.xyy.ec.pop.erp.hx.helper.HXHelper;
import com.xyy.ec.pop.erp.hx.po.hx.*;
import com.xyy.ec.pop.erp.hx.po.hx.orderPo.BillDetail;
import com.xyy.ec.pop.erp.hx.po.hx.orderPo.BillHead;
import com.xyy.ec.pop.erp.hx.po.pop.ApiRPCResult;
import com.xyy.ec.pop.erp.hx.po.pop.dto.*;
import com.xyy.ec.pop.erp.hx.service.PopErpTaskService;
import com.xyy.ec.pop.erp.hx.service.PopService;
import com.xyy.ec.pop.erp.hx.utils.DateUtils;
import com.xyy.ec.pop.erp.hx.utils.MD5Util;
import com.xyy.ec.pop.erp.hx.utils.ReflectionUtils;
import com.xyy.ec.pop.erp.hx.utils.hx.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PopErpTaskServiceImpl implements PopErpTaskService {
    /**
     * 配置信息
     */
    @Autowired
    HXTaskConfig comentCfg;
    @Autowired
    private SeaflyApi seaflyApi;
    @Autowired
    private PopService popService;

    /**
     * 商品全量
     */
    @Override
    public void syncProductFullToPop() {
        //构建参数
        Map<String, Object> paramMap = buildProductFullParam(1, 1);
        SfApiConfig apiConfig = SfApiConfig.builder().domainAddress(comentCfg.getDomainAddress()).appId(comentCfg.getHxAppId()).appKey(comentCfg.getHxAppKey()).build();
        SeaFlyResult result = seaflyApi.doPost(comentCfg.getGetproductsUrl(), paramMap, SeaFlyResult.class, apiConfig);
        if (result == null || result.getStatus() != 200) {
            log.warn("PopErpTaskHXServiceImpl.syncProductFullToPop#接口返回状态异常 result：{}", JSON.toJSONString(result));
            return;
        }
        SeaFlyDataResult data = JSON.parseObject(JSON.toJSONString(result.getData()), SeaFlyDataResult.class);
        Integer total;
        if (data == null || (total = data.getTotal()) == null) {
            log.warn("PopErpTaskHXServiceImpl.syncProductFullToPop#接口返回数量为空 result：{}", JSON.toJSONString(result));
            return;
        }
        int pageSize = comentCfg.getProductAllBatchSize();
        int totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        //分批查询上报
        for (int pageNum = 1; pageNum < totalPage; pageNum++) {
            stepSyncProductFullToPop(pageNum, pageSize, apiConfig);
        }
    }

    /**
     * 分批查询上报
     *
     * @param pageNum
     * @param pageSize
     * @param apiConfig
     */
    private void stepSyncProductFullToPop(Integer pageNum, Integer pageSize, SfApiConfig apiConfig) {
        //构建参数
        Map<String, Object> paramMap = buildProductFullParam(pageNum, pageSize);
        SeaFlyResult result = seaflyApi.doPostPlus(comentCfg.getGetproductsUrl(), paramMap, SeaFlyResult.class, apiConfig);
        if (result == null || result.getStatus() != 200) {
            log.warn("PopErpTaskHXServiceImpl.stepSyncProductFullToPop#接口返回状态异常 result：{}", JSON.toJSONString(result));
            return;
        }
        SeaFlyDataResult data = JSON.parseObject(JSON.toJSONString(result.getData()), SeaFlyDataResult.class);
        if (data == null || CollectionUtils.isEmpty(data.getRows())) {
            log.warn("PopErpTaskHXServiceImpl.syncProductFullToPop#接口返回数据列表为空 result：{}", JSON.toJSONString(result));
            return;
        }
        //海翔商品全量列表数据
        List<ProductFullHXPo> rows = JsonUtils.jsonToList(JsonUtils.objectToJson(data.getRows()), ProductFullHXPo.class);
        //海翔商品表ids
        List<String> code = new ArrayList<>();
        if (comentCfg.getNumberType().equals("code")) {
            code = rows.stream().map(m -> m.getCode()).distinct().collect(Collectors.toList());
        } else {
            code = rows.stream().map(m -> m.getPid()).distinct().collect(Collectors.toList());
        }
        //补充建议零售价、单体售价、连锁售价、远近生产日期、远近效期信息
        //查询库存map信息  只同步库存大于0
        Map<Object, List<ProductStockHXPo>> stockMap = getStockMap(code, apiConfig);
        if (CollectionUtils.isEmpty(stockMap)) {
            return;
        }
        //转POP Dto对象
        List<PopErpSkuForInsertDto> popErpSkuForInsertDtos = HXHelper.convertToPopErpSkuDtos(rows, stockMap, comentCfg);
        if (CollectionUtils.isEmpty(popErpSkuForInsertDtos)) {
            return;
        }
        //构建POP请求参数
        TaskQueryParam taskQueryParam = buildPopTaskQueryParam(TaskEnum.PRODUCT_FULL.getTaskId(), popErpSkuForInsertDtos);
        //商品上报
        ApiRPCResult<Boolean> apiRPCResult = popService.pushDataInfo(taskQueryParam);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("PopErpTaskHXServiceImpl.syncProductFullToPop#任务上报失败, orgId:{}, apiRPCResult：{}", comentCfg.getPopOrgId(), JSON.toJSONString(apiRPCResult));
        } else {
            log.info("商品信息上报成功{}条 当前时间: {}", popErpSkuForInsertDtos.size(), DateUtil.now());
        }
    }

    private Map<Object, List<ProductStockHXPo>> getStockMap(List<String> pids, SfApiConfig apiConfig) {
        if (CollectionUtils.isEmpty(pids)) {
            return Maps.newHashMap();
        }
        //构建查询库存参数
        Map<String, Object> paramMap = buildStockParam(1, pids.size(), pids.stream().map(pid -> String.valueOf(pid)).collect(Collectors.toList()));
        //http调用海翔库存查询接口
        SeaFlyResult<String> result = seaflyApi.doPostPlus(comentCfg.getGetstorehouseUrl(), paramMap, SeaFlyResult.class, apiConfig);
        if (result == null || result.getData() == null) {
            return Maps.newHashMap();
        }
        SeaFlyDataResult dataResult = JSON.parseObject(result.getData(), SeaFlyDataResult.class);
        List<ProductStockHXPo> stocks = JsonUtils.jsonToList(JsonUtils.objectToJson(dataResult.getRows()), ProductStockHXPo.class);
        if (!CollectionUtils.isEmpty(stocks) && StringUtils.isNotEmpty(comentCfg.getOrgList())) {
            HashSet<String> orgIds = new HashSet<>(Arrays.asList(comentCfg.getOrgList().split(",")));

            stocks = stocks.stream().filter(stock -> orgIds.contains(String.valueOf(stock.getYid()))) // 整数转字符串
                    .collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(stocks) && StringUtils.isNotEmpty(comentCfg.getWarehouseList())) {
                HashSet<String> warehouseIds = new HashSet<>(Arrays.asList(comentCfg.getWarehouseList().split(",")));

                stocks = stocks.stream().filter(stock -> warehouseIds.contains(String.valueOf(stock.getSid()))) // 整数转字符串
                        .collect(Collectors.toList());
            }
        }
        Map<Object, List<ProductStockHXPo>> pidStocksMap = new HashMap<>();
        if (CollectionUtils.isEmpty(stocks)) {
            return pidStocksMap;
        }
        if (comentCfg.getNumberType().equals("code")) {
            pidStocksMap = stocks.stream().collect(Collectors.groupingBy(item -> item.getPcode()));
        } else {
            pidStocksMap = stocks.stream().collect(Collectors.groupingBy(item -> item.getPid()));
        }
        return pidStocksMap;
    }

    private Map<String, Object> buildStockParam(Integer pageNum, Integer pageSize, List<String> pidList) {
        String pids = null;
        if (!CollectionUtils.isEmpty(pidList)) {
            pids = pidList.stream().collect(Collectors.joining(";"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("accountName", comentCfg.getHxAccountName());
        paramMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
        paramMap.put("page", String.valueOf(pageNum));
        paramMap.put("rows", String.valueOf(pageSize));
        //查询条件
        if (StringUtils.isNotBlank(pids)) {
            if ("code".equals(comentCfg.getNumberType())) {
                paramMap.put("pCode", pids);
            } else {
                paramMap.put("pids", pids);
            }
            paramMap.put("rows", String.valueOf(pidList.size() * 10));
        }
        return paramMap;
    }

    private Map<Object, SeaFlyPricePo> getPriceMap(List<String> pids, SfApiConfig apiConfig) {
        if (CollectionUtils.isEmpty(pids)) {
            return Maps.newHashMap();
        }
        //构建查询价格参数
        Map<String, Object> paramMap = buildPriceParam(1, pids.size(), pids);
        log.info("价格请求参数:{}", JSON.toJSONString(paramMap));
        //http调用海翔价格查询接口
        SeaFlyResult<String> result = seaflyApi.doPostPlus(comentCfg.getGetpriceUrl(), paramMap, SeaFlyResult.class, apiConfig);
        if (result == null || result.getData() == null) {
            return Maps.newHashMap();
        }
        SeaFlyDataResult data = JsonUtils.jsonToPojo(JsonUtils.objectToJson(result.getData()), SeaFlyDataResult.class);
        if (data == null || CollectionUtils.isEmpty(data.getRows())) {
            return Maps.newHashMap();
        }
        List<SeaFlyPricePo> prices = JsonUtils.jsonToList(JsonUtils.objectToJson(data.getRows()), SeaFlyPricePo.class);
        // 仪陇本草堂只取基本单位对应的价格
        prices = prices.stream().filter(seaFlyPricePo -> seaFlyPricePo.getUnittype() != null && seaFlyPricePo.getUnittype() == Integer.valueOf(comentCfg.getQueryPriceType())).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(prices)) {
            return Maps.newHashMap();
        }
        Map<Object, SeaFlyPricePo> pidPricesMap = new HashMap<>();
        if (comentCfg.getNumberType().equals("code")) {
            pidPricesMap = prices.stream().collect(Collectors.toMap(SeaFlyPricePo::getPcode, Function.identity(), (x, y) -> x));
        } else {
            pidPricesMap = prices.stream().collect(Collectors.toMap(SeaFlyPricePo::getPid, Function.identity(), (x, y) -> x));
        }
        return pidPricesMap;


    }


    private <T> Map<String, Object> buildPriceParam(Integer pageNum, Integer pageSize, List<T> pidList) {
        String pids = null;
        if (!CollectionUtils.isEmpty(pidList)) {
            pids = pidList.stream().map(pid -> String.valueOf(pid)).collect(Collectors.joining(";"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("accountName", comentCfg.getHxAccountName());
        paramMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
        paramMap.put("page", String.valueOf(pageNum));
        paramMap.put("rows", String.valueOf(pageSize));
        // （-1，所有价格，0、基本单位价格，1、单位1价格，2、单位2价格，3、单位3价格）
        paramMap.put("unittype", comentCfg.getQueryPriceType());
        //查询条件
        if (StringUtils.isNotBlank(pids)) {
            if ("code".equals(comentCfg.getNumberType())) {
                paramMap.put("codes", pids);
            } else {
                paramMap.put("pids", pids);
            }
        }
        return paramMap;
    }

    private Map<String, Object> buildProductFullParam(Integer pageNum, Integer pageSize) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("accountName", comentCfg.getHxAccountName());
        paramMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
        paramMap.put("page", String.valueOf(pageNum));
        paramMap.put("rows", String.valueOf(pageSize));
        paramMap.put("nozero", "1");// 商品有无库存（0：所有商品，1：有库存的商品）
        return paramMap;
    }

    /**
     * 商品库存
     */
    @Override
    public void syncProductStockToPop() {
        TaskQueryParam taskQueryParam = buildPopTaskQueryParam(TaskEnum.PRODUCT_STOCK.getTaskId(), null);
        //从POP平台查询erpCodes
        ApiRPCResult<ResultDto> apiRPCResult = popService.queryTaskCondition(taskQueryParam);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("PopErpTaskServiceImpl.syncProductStockToPop#查询库存同步条件失败 orgId：{}，apiRPCResult：{}", comentCfg.getPopOrgId(), JSON.toJSONString(apiRPCResult));
        }
        if (apiRPCResult.getData() == null) {
            log.warn("PopErpTaskHXServiceImpl.syncProductStockToPop#没有可同步的商品 orgId：{}，apiRPCResult：{}", comentCfg.getPopOrgId(), JSON.toJSONString(apiRPCResult));
            return;
        }
        ResultDto resultDto = JSON.parseObject(JSON.toJSONString(apiRPCResult.getData()), ResultDto.class);
        TaskConditionDto taskConditionDto = JSON.parseObject(resultDto.getDataJson(), TaskConditionDto.class);
        //对应商品表的pid字段
        List<String> listQueryParam = taskConditionDto.getListQueryParam();
        //分批查询，避免数据量过多，汇总总条数后，在分批查询上报
        List<List<String>> queryPartition = Lists.partition(listQueryParam, comentCfg.getStockBatchSize());
        SfApiConfig apiConfig = SfApiConfig.builder().domainAddress(comentCfg.getDomainAddress()).appId(comentCfg.getHxAppId()).appKey(comentCfg.getHxAppKey()).build();
        // erp接口返回有库存的po
        List<PopErpSkuStockV2Dto> totalHxHaveStockPos = new ArrayList<>();
        //分批查询上报
        for (List<String> erpCodes : queryPartition) {
            List<PopErpSkuStockV2Dto> rows = stepSyncProductStockToPop(apiConfig, erpCodes);
            if (CollectionUtils.isEmpty(rows)) {
                continue;
            }
            totalHxHaveStockPos.addAll(rows);
        }
        processZeroStock(listQueryParam, totalHxHaveStockPos);
    }

    private List<PopErpSkuStockV2Dto> stepSyncProductStockToPop(SfApiConfig apiConfig, List<String> erpCodes) {
        //构建参数
        Map<String, Object> paramMap = buildStockParam(1, erpCodes.size() * 10, erpCodes);
        //调用海翔http接口查询库存信息
        SeaFlyResult<String> result = seaflyApi.doPostPlus(comentCfg.getGetstorehouseUrl(), paramMap, SeaFlyResult.class, apiConfig);
        if (result == null || result.getStatus() != 200) {
            log.warn("PopErpTaskHXServiceImpl.stepSyncProductFullToPop#接口返回状态异常 result：{} paramMap: {}", JSON.toJSONString(result), JSON.toJSONString(paramMap));
            //不抛异常会置零
            throw new RuntimeException("海翔接口异常PopErpTaskHXServiceImpl.stepSyncProductStockToPop");
        }
        try {
            SeaFlyDataResult seaFlyDataResult = JSONObject.parseObject(result.getData(), SeaFlyDataResult.class);
            if (seaFlyDataResult == null || CollectionUtils.isEmpty(seaFlyDataResult.getRows())) {
                log.warn("PopErpTaskHXServiceImpl.syncProductFullToPop#接口返回数据列表为空 seaFlyDataResult：{}", JSON.toJSONString(seaFlyDataResult));
                return Collections.emptyList();
            }

            //海翔商品库存列表数据
            List<ProductStockHXPo> rows = JsonUtils.jsonToList(JsonUtils.objectToJson(seaFlyDataResult.getRows()), ProductStockHXPo.class);
            if (!CollectionUtils.isEmpty(rows) && StringUtils.isNotEmpty(comentCfg.getOrgList())) {
                HashSet<String> orgIds = new HashSet<>(Arrays.asList(comentCfg.getOrgList().split(",")));

                rows = rows.stream().filter(stock -> orgIds.contains(String.valueOf(stock.getYid()))) // 整数转字符串
                        .collect(Collectors.toList());

                if (!CollectionUtils.isEmpty(rows) && StringUtils.isNotEmpty(comentCfg.getWarehouseList())) {
                    HashSet<String> warehouseIds = new HashSet<>(Arrays.asList(comentCfg.getWarehouseList().split(",")));

                    rows = rows.stream().filter(stock -> warehouseIds.contains(String.valueOf(stock.getSid()))) // 整数转字符串
                            .collect(Collectors.toList());
                }
            }
            if (CollectionUtils.isEmpty(rows)) {
                log.warn("PopErpTaskHXServiceImpl.syncProductFullToPop#过滤后的商品库存数据为空 orgId:{}", comentCfg.getPopOrgId());
                return Collections.emptyList();
            }
            Map<String, List<ProductStockHXPo>> pidStockMap = null;
            if (comentCfg.getNumberType().equals("code")) {
                pidStockMap = rows.stream().collect(Collectors.groupingBy(ProductStockHXPo::getPcode));
            } else {
                pidStockMap = rows.stream().collect(Collectors.groupingBy(po -> String.valueOf(po.getPid())));
            }
            //转POP Dto对象
            List<PopErpSkuStockV2Dto> popErpSkuStockDtos = HXHelper.convertToPopErpSkuStockDtos(pidStockMap);
            //构建POP请求参数
            TaskQueryParam taskQueryParam = buildPopTaskQueryParam(TaskEnum.PRODUCT_STOCK.getTaskId(), popErpSkuStockDtos);
            //商品上报
            ApiRPCResult<Boolean> apiRPCResult = popService.pushDataInfo(taskQueryParam);
            if (apiRPCResult == null || apiRPCResult.isFail() || !apiRPCResult.getData()) {
                log.warn("PopErpTaskHXServiceImpl.stepSyncProductStockToPop#任务上报失败 orgId:{}, apiRPCResult：{}", comentCfg.getPopOrgId(), JSON.toJSONString(apiRPCResult));
            } else {
                log.info("商品库存信息上报成功{}条 当前时间: {}", popErpSkuStockDtos.size(), DateUtil.now());
            }
            return popErpSkuStockDtos;
        } catch (Exception e) {
            log.error("stepSyncProductStockToPop error: orgId:{}", comentCfg.getPopOrgId(), e);
            return Collections.emptyList();
        }
    }

    /**
     * 处理erp接口未返库存的商品库存置为0
     *
     * @param listQueryParam
     * @param totalHxHaveStockPos
     */
    private void processZeroStock(List<String> listQueryParam, List<PopErpSkuStockV2Dto> totalHxHaveStockPos) {
        List<String> totalHxHaveStockPids = totalHxHaveStockPos.stream().map(PopErpSkuStockV2Dto::getErpCode).collect(Collectors.toList());
        listQueryParam.removeAll(totalHxHaveStockPids);
        if (!CollectionUtils.isEmpty(listQueryParam)) {
            List<List<String>> stockZeroList = Lists.partition(listQueryParam, comentCfg.getStockBatchSize());
            for (List<String> list : stockZeroList) {
                //转POP Dto对象
                List<PopErpSkuStockV2Dto> popErpSkuStockDtos = new ArrayList<>();
                for (String erpCode : list) {
                    PopErpSkuStockV2Dto popErpSkuStockV2Dto = new PopErpSkuStockV2Dto();
                    popErpSkuStockV2Dto.setErpCode(erpCode);
                    popErpSkuStockV2Dto.setAvailableQyt(0);
                    popErpSkuStockDtos.add(popErpSkuStockV2Dto);
                }
                //构建POP请求参数
                TaskQueryParam stockTaskQueryParam = buildPopTaskQueryParam(TaskEnum.PRODUCT_STOCK.getTaskId(), popErpSkuStockDtos);
                //商品上报
                ApiRPCResult<Boolean> rpcResult = popService.pushDataInfo(stockTaskQueryParam);
                if (rpcResult == null || rpcResult.isFail() || !rpcResult.getData()) {
                    log.warn("PopErpTaskHXServiceImpl.syncProductFullToPop#库存置为0上报失败 rpcResult：{}", JSON.toJSONString(rpcResult));
                }
            }
        }
    }

    /**
     * 商品价格
     */
    @Override
    public void syncProductPriceToPop() {
        TaskQueryParam taskQueryParam = buildPopTaskQueryParam(TaskEnum.PRODUCT_PRICE.getTaskId(), null);
        //从POP平台查询erpCodes
        ApiRPCResult<ResultDto> apiRPCResult = popService.queryTaskCondition(taskQueryParam);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#查询价格同步条件失败 orgId：{}，apiRPCResult：{}", comentCfg.getPopOrgId(), JSON.toJSONString(apiRPCResult));
            return;
        }
        if (apiRPCResult.getData() == null) {
            log.warn("#没有可同步的商品 orgId：{}，apiRPCResult：{}", comentCfg.getPopOrgId(), JSON.toJSONString(apiRPCResult));
            return;
        }
        ResultDto resultDto = JSON.parseObject(JSON.toJSONString(apiRPCResult.getData()), ResultDto.class);
        TaskConditionDto taskConditionDto = JSON.parseObject(resultDto.getDataJson(), TaskConditionDto.class);
        //对应商品表的pid字段
        List<String> listQueryParam = taskConditionDto.getListQueryParam();
        //分批查询，避免数据量过多，汇总总条数后，在分批查询上报
        List<List<String>> queryPartition = Lists.partition(listQueryParam, comentCfg.getPriceBatchSize());
        SfApiConfig apiConfig = SfApiConfig.builder().domainAddress(comentCfg.getDomainAddress()).appId(comentCfg.getHxAppId()).appKey(comentCfg.getHxAppKey()).build();


        for (List<String> erpCodes : queryPartition) {
            //构建参数
            Map<String, Object> paramMap = buildPriceParam(1, erpCodes.size(), erpCodes);
            SeaFlyResult<String> result = seaflyApi.doPostPlus(comentCfg.getGetpriceUrl(), paramMap, SeaFlyResult.class, apiConfig);
            if (result == null || result.getStatus() != 200) {
                log.warn("#syncProductPriceToPop接口返回状态异常, result：{}", JSON.toJSONString(result));
                continue;
            }
            SeaFlyDataResult seaFlyDataResult = JsonUtils.jsonToPojo(JsonUtils.objectToJson(result.getData()), SeaFlyDataResult.class);
            if (seaFlyDataResult == null || CollectionUtils.isEmpty(seaFlyDataResult.getRows())) {
                log.warn("#syncProductPriceToPop接口返回数量为空 result：{}", JSON.toJSONString(seaFlyDataResult));
                continue;
            }
            //转POP Dto对象
            List<SeaFlyPricePo> seaFlyPricePos = JsonUtils.jsonToList(JsonUtils.objectToJson(seaFlyDataResult.getRows()), SeaFlyPricePo.class);
            seaFlyPricePos = seaFlyPricePos.stream().filter(seaFlyPricePo -> seaFlyPricePo.getUnittype() != null && seaFlyPricePo.getUnittype() == Integer.valueOf(comentCfg.getQueryPriceType())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(seaFlyPricePos)) {
                continue;
            }
            log.info("海翔商品价格:{}", JSON.toJSONString(seaFlyPricePos));
            List<PopErpSkuPriceDto> popErpSkuPriceDtos = new ArrayList<>();
            seaFlyPricePos.forEach(seaFlyPricePo -> {
                PopErpSkuPriceDto popErpSkuPriceDto = new PopErpSkuPriceDto();
                popErpSkuPriceDto.setErpCode(String.valueOf("code".equals(comentCfg.getNumberType()) ? seaFlyPricePo.getPcode() : seaFlyPricePo.getPid()));
                BigDecimal price = (BigDecimal) ReflectionUtils.getFieldValue(seaFlyPricePo, comentCfg.getPrice());
                popErpSkuPriceDto.setMonomerPrice(price);
                popErpSkuPriceDto.setChainPrice(price);
                popErpSkuPriceDto.setBasePrice(price);
                popErpSkuPriceDtos.add(popErpSkuPriceDto);
            });
            //构建POP请求参数
            taskQueryParam = buildPopTaskQueryParam(TaskEnum.PRODUCT_PRICE.getTaskId(), popErpSkuPriceDtos);
            //商品上报
            ApiRPCResult<Boolean> pushDataApiRPCResult = popService.pushDataInfo(taskQueryParam);
            if (pushDataApiRPCResult == null || pushDataApiRPCResult.isFail() || !pushDataApiRPCResult.getData()) {
                log.warn("syncProductPriceToPop#任务上报失败 orgId:{}, apiRPCResult：{}", comentCfg.getPopOrgId(), JSON.toJSONString(pushDataApiRPCResult));
            } else {
                log.info("商品价格信息上报成功{}条 当前时间: {}", popErpSkuPriceDtos.size(), DateUtil.now());
            }
        }
    }

    /**
     * 客户信息上报
     */
    @Override
    public void syncCustomerToPop() {
//构建参数
        Map<String, Object> paramMap = buildCustomerParam(1, 1);
        SfApiConfig apiConfig = SfApiConfig.builder().domainAddress(comentCfg.getDomainAddress()).appId(comentCfg.getHxAppId()).appKey(comentCfg.getHxAppKey()).build();
        //第一次查询，为了获取数量
        SeaFlyResult result = seaflyApi.doPostPlus(comentCfg.getGetclientsUrl(), paramMap, SeaFlyResult.class, apiConfig);
        if (result == null || result.getStatus() != 200) {
            log.warn("PopErpTaskHXServiceImpl.syncCustomerToPop#接口返回状态异常 result：{}", JSON.toJSONString(result));
            return;
        }
        SeaFlyDataResult data = JSON.parseObject(JSON.toJSONString(result.getData()), SeaFlyDataResult.class);
        Integer total;
        if (data == null || (total = data.getTotal()) == null) {
            log.warn("PopErpTaskHXServiceImpl.syncCustomerToPop#接口返回数量为空 result：{}", JSON.toJSONString(result));
            return;
        }
        int pageSize = comentCfg.getCustomerBatchSize();
        int totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        //分批查询上报
        for (int pageNum = 1; pageNum <= totalPage; pageNum++) {
            stepSyncCustomerToPop(pageNum, pageSize, apiConfig);
        }
    }

    private void stepSyncCustomerToPop(int pageNum, Integer pageSize, SfApiConfig apiConfig) {
        //构建参数
        Map<String, Object> paramMap = buildCustomerParam(pageNum, pageSize);
        SeaFlyResult result = seaflyApi.doPostPlus(comentCfg.getGetclientsUrl(), paramMap, SeaFlyResult.class, apiConfig);
        if (result == null || result.getStatus() != 200) {
            log.warn("PopErpTaskHXServiceImpl.stepSyncCustomerToPop#接口返回状态异常 result：{}", JSON.toJSONString(result));
            return;
        }
        SeaFlyDataResult data = JSON.parseObject(JSON.toJSONString(result.getData()), SeaFlyDataResult.class);
        if (data == null || CollectionUtils.isEmpty(data.getRows())) {
            log.warn("PopErpTaskHXServiceImpl.stepSyncCustomerToPop#接口返回数据列表为空 result：{}", JSON.toJSONString(result));
            return;
        }
        //海翔查询客户列表数据
        List<CustomerHXPo> rows = JsonUtils.jsonToList(JsonUtils.objectToJson(data.getRows()), CustomerHXPo.class);
        //转POP Dto对象
        List<PopErpClientInfoDto> popErpClientInfoDtos = HXHelper.convertToPopErpClientInfoDtos(rows);
        //构建POP请求参数
        TaskQueryParam taskQueryParam = buildPopTaskQueryParam(TaskEnum.CLIENT_INFO.getTaskId(), popErpClientInfoDtos);
        //客户信息上报
        ApiRPCResult<Boolean> apiRPCResult = popService.pushDataInfo(taskQueryParam);
        if (apiRPCResult == null || apiRPCResult.isFail() || !apiRPCResult.getData()) {
            log.warn("PopErpTaskHXServiceImpl.stepSyncCustomerToPop#任务上报失败 accountName:{}, apiRPCResult：{}", comentCfg.getHxAccountName(), JSON.toJSONString(apiRPCResult));
            return;
        } else {
            log.info("客户信息上报成功{}条 当前时间: {}", popErpClientInfoDtos.size(), DateUtil.now());
        }
    }

    private Map<String, Object> buildCustomerParam(Integer pageNum, Integer pageSize) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("accountName", comentCfg.getHxAccountName());
        paramMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
        if (comentCfg.getModifyDate() > 0) {
            paramMap.put("modifyDate", LocalDate.now().minusDays(comentCfg.getModifyDate()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));//获取当前日期前3天
        }
        {
            paramMap.put("modifyDate", "2022-01-01");
        }
        paramMap.put("page", String.valueOf(pageNum));
        paramMap.put("rows", String.valueOf(pageSize));
        //往来单位类型（0：客户，1：供应商，2：两者皆是）
        paramMap.put("csflag", "0");
        //是否正常客户
        paramMap.put("deleted", "0");
        return paramMap;
    }

    /**
     * 订单导入
     */
    @Override
    public void syncOrderToMerchant() {
        //构建查询pop参数
        TaskQueryParam taskQueryParam = buildPopTaskQueryParam(TaskEnum.ORDER_TOTAL.getTaskId(), null);
        //拉取POP订单
        ApiRPCResult<ResultDto> apiRPCResult = popService.pullDataInfo(taskQueryParam);
        if (comentCfg.getIsOutPutBizLog()) {
            log.warn("PopErpTaskHXServiceImpl.syncOrderToSeaFly.pullDataInfo#{}", JSON.toJSONString(apiRPCResult));
        }
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("PopErpTaskHXServiceImpl.syncOrderToMerchant#订单下推失败 orgId：{}，apiRPCResult：{}", comentCfg.getPopOrgId(), JSON.toJSONString(apiRPCResult));
            return;
        }

        if (apiRPCResult.getData() == null) {
            return;
        }
        ResultDto resultDto = JSON.parseObject(JSON.toJSONString(apiRPCResult.getData()), ResultDto.class);
        String dataJson = resultDto.getDataJson();
        //解析订单数据
        List<SellerOrderInfoDto> orderInfoDtos = JSON.parseArray(dataJson, SellerOrderInfoDto.class);
        if (comentCfg.getIsOutPutBizLog()) {
            log.warn("PopErpTaskHXServiceImpl.syncOrderToSeaFly.orderInfoDtos#{}", JSON.toJSONString(orderInfoDtos));
        }
        SfApiConfig apiConfig = SfApiConfig.builder().domainAddress(comentCfg.getDomainAddress()).appId(comentCfg.getHxAppId()).appKey(comentCfg.getHxAppKey()).build();
        //转化成海翔订单对象
        convertToHXOrderList(orderInfoDtos, apiConfig);
    }

    private void convertToHXOrderList(List<SellerOrderInfoDto> orderInfoDtos, SfApiConfig config) {

        for (SellerOrderInfoDto sellerOrderInfoDto : orderInfoDtos) {
            log.info("获取到药帮忙订单信息: {}", JSON.toJSONString(sellerOrderInfoDto));
            Map<String, Object> indexData = new HashMap<>();
            indexData.put("billid", 0);
            indexData.put("billdate", DateUtils.format(sellerOrderInfoDto.getOrderCreateTime(), DateUtils.SHORT_DATE_FORMAT_STR));
            indexData.put("billnumber", sellerOrderInfoDto.getOrderNo());
            indexData.put("billtype", 30);
            BigDecimal orderPayAmount = sellerOrderInfoDto.getPayAmount().subtract(Optional.ofNullable(sellerOrderInfoDto.getFreight()).orElse(BigDecimal.ZERO));
            // indexData.put("ssmoney", orderPayAmount.doubleValue());
            indexData.put("billtotal", orderPayAmount.doubleValue());
            indexData.put("billqty", (Double) sellerOrderInfoDto.getSellerOrderDetailLists().stream().map(SellerOrderDetailDto::getPurchaseNumDecimal).reduce(BigDecimal::add).map(a -> a.doubleValue()).get());
            CustomerHXPo po = getCustomerinfo(config, sellerOrderInfoDto);
            if (Objects.isNull(po)) {
                log.warn("未查询到客户编码-{} 订单号: {}", sellerOrderInfoDto.getVenderCode(), sellerOrderInfoDto.getOrderNo());
                continue;
            }
            //客户ID
            indexData.put("cid", po.getCid());
            //登录者ID
            indexData.put("uid", comentCfg.getDocumentMakerId());
            //经手人ID
            indexData.put("eid", comentCfg.getHandlerId());
            //出库仓库 出库仓库id
            if (StringUtils.isNotBlank(comentCfg.getOutStoreId())) {
                indexData.put("ssid", comentCfg.getOutStoreId());
            }
            //部门
            if (StringUtils.isNotBlank(comentCfg.getOrgList())) {
                indexData.put("yid", comentCfg.getOrgList());
            }
            //收货人地址
            indexData.put("contactaddress", sellerOrderInfoDto.getPickAddress());
            //收货人
            indexData.put("contactman", sellerOrderInfoDto.getPickName());
            //收货电话
            indexData.put("contactphone", sellerOrderInfoDto.getPickPhone());

            List<Map<String, Object>> detailDatas = new ArrayList<>();
            int rowIndex = 1;
            for (SellerOrderDetailDto sellerOrderDetailDto : sellerOrderInfoDto.getSellerOrderDetailLists()) {
                Map<String, Object> detailData = new HashMap<>();
                Double payAmount = sellerOrderDetailDto.getPayAmount().doubleValue();
                Double price = (sellerOrderDetailDto.getPayAmount().divide(BigDecimal.valueOf(sellerOrderDetailDto.getPurchaseNum()), 6, BigDecimal.ROUND_HALF_UP)).doubleValue();
                String erpCode = sellerOrderDetailDto.getErpCode();
                String billunit = "";
                //蓬安本草堂要上传外码
                if ("code".equals(comentCfg.getNumberType())) {
                    ProductFullHXPo pinfo = getPinfo(config, sellerOrderDetailDto);
                    if (Objects.isNull(pinfo)) {
                        log.warn("海翔未查询到商品:{}", sellerOrderDetailDto.getErpCode());
                        continue;
                    }
                    erpCode = String.valueOf(pinfo.getPid());
                    billunit = pinfo.getUnit();
                }
                detailData.put("pid", erpCode);
                detailData.put("billid", 0);
                detailData.put("unitrate", 1);
                detailData.put("qty", sellerOrderDetailDto.getPurchaseNumDecimal().doubleValue());
                detailData.put("quantity", sellerOrderDetailDto.getPurchaseNumDecimal().doubleValue());
                detailData.put("price", price);
                detailData.put("total", payAmount);
                detailData.put("discount", 1);
                detailData.put("cxdiscount", 1);
                detailData.put("userdiscount", 1);
                detailData.put("discountprice", price);
                detailData.put("discounttotal", payAmount);
                detailData.put("taxprice", price);
                detailData.put("taxrate", 0);
                detailData.put("taxtotal", payAmount);
                detailData.put("taxmoney", 0);
                detailData.put("rowindex", rowIndex++);
                detailData.put("billunit", billunit);
                detailData.put("remark", sellerOrderDetailDto.getOrderDetailId());
                detailDatas.add(detailData);
            }
            Map<String, Object> dataParamMap = new HashMap<>();
            dataParamMap.put("billtype", 30);
            // 单据是否需要直接过账（true：过账，false：草稿）
            dataParamMap.put("audit", false);
            dataParamMap.put("indexData", indexData);
            dataParamMap.put("indexExData", new HashMap<>());
            dataParamMap.put("detailData", detailDatas);
            //构建参数
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("accountName", comentCfg.getHxAccountName());
            paramMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
            SeaFlyResult result = seaflyApi.doPostPlus(comentCfg.getInputbillsUrl(), paramMap, dataParamMap, SeaFlyResult.class, config);
            if (result.getStatus() == 200) {
                log.info("海翔订单导入接口信息: {},导入参数: {}", JSON.toJSONString(result), JSON.toJSONString(dataParamMap));
            }
            List<SellerOrderCallBackDto> sellerOrderCallBackDtos = new ArrayList<>();
            SellerOrderCallBackDto sellerOrderCallBackDto = new SellerOrderCallBackDto();
            sellerOrderCallBackDto.setOrderNo(sellerOrderInfoDto.getOrderNo());
            sellerOrderCallBackDto.setOrgId(sellerOrderInfoDto.getOrgId());
            sellerOrderCallBackDto.setType(1);
            sellerOrderCallBackDto.setResult(true);
            if (result == null || result.getStatus() != 200) {
                sellerOrderCallBackDto.setResult(false);
                log.warn("平台订单下推异常:orgId:" + sellerOrderInfoDto.getOrgId() + ", orderNo:" + sellerOrderInfoDto.getOrderNo() + " 接口返回: " + JSON.toJSONString(result));
            }
            sellerOrderCallBackDtos.add(sellerOrderCallBackDto);
            TaskQueryParam taskQueryParam = buildPopTaskQueryParam(null, sellerOrderCallBackDtos);
            popService.callbackForPullTask(taskQueryParam);
        }


    }


    private ProductFullHXPo getPinfo(SfApiConfig config, SellerOrderDetailDto sellerOrderDetailDto) {
        //构建参数
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("accountName", comentCfg.getHxAccountName());
        paramMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
        paramMap.put("page", String.valueOf(1));
        paramMap.put("rows", String.valueOf(10));
        paramMap.put("dim", sellerOrderDetailDto.getErpCode());
        SeaFlyResult result = seaflyApi.doPostPlus(comentCfg.getGetproductsUrl(), paramMap, SeaFlyResult.class, config);
        if (result == null || result.getStatus() != 200) {
            log.warn("PopErpTaskHXServiceImpl.getPinfo#接口返回状态异常 result：{}", JSON.toJSONString(result));
            return null;
        }
        SeaFlyDataResult data = JSON.parseObject(JSON.toJSONString(result.getData()), SeaFlyDataResult.class);
        Integer total;
        if (data == null || (total = data.getTotal()) == null) {
            log.warn("PopErpTaskHXServiceImpl.getPinfo#接口返回数量为空 result：{}", JSON.toJSONString(result));
            return null;
        }
        //海翔商品全量列表数据
        List<ProductFullHXPo> rows = JsonUtils.jsonToList(JsonUtils.objectToJson(data.getRows()), ProductFullHXPo.class);
        return rows.stream().filter(r -> sellerOrderDetailDto.getErpCode().equals(r.getCode())).findFirst().orElse(null);
    }


    private CustomerHXPo getCustomerinfo(SfApiConfig config, SellerOrderInfoDto dto) {
        if (StringUtils.isBlank(dto.getVenderCode())) {
            return null;
        }
        //构建参数
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("dim", dto.getVenderCode());
        paramMap.put("accountName", comentCfg.getHxAccountName());
        paramMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
        paramMap.put("page", "1");
        paramMap.put("rows", "10");
        //往来单位类型（0：客户，1：供应商，2：两者皆是）
        paramMap.put("csflag", "0");
        paramMap.put("deleted", "0");
        //第一次查询，为了获取数量
        SeaFlyResult result = seaflyApi.doPostPlus(comentCfg.getGetclientsUrl(), paramMap, SeaFlyResult.class, config);
        if (result == null || result.getStatus() != 200) {
            log.warn("PopErpTaskHXServiceImpl.getCustomerinfo#接口返回状态异常 result：{}", JSON.toJSONString(result));
            return null;
        }
        SeaFlyDataResult data = JSON.parseObject(JSON.toJSONString(result.getData()), SeaFlyDataResult.class);
        Integer total;
        if (data == null || (total = data.getTotal()) == null) {
            log.warn("PopErpTaskHXServiceImpl.getCustomerinfo#接口返回数量为空 result：{}", JSON.toJSONString(result));
            return null;
        }
        //海翔商品全量列表数据
        //海翔查询客户列表数据
        List<CustomerHXPo> rows = JsonUtils.jsonToList(JsonUtils.objectToJson(data.getRows()), CustomerHXPo.class);
        if (CollectionUtils.isEmpty(rows)) {
            return null;
        }
        return rows.stream().filter(r -> Objects.nonNull(r.getName())).findFirst().orElse(null);
    }


    /**
     * 客户导入
     */
    @Override
    public void syncNoneOpenCustomerToMerchant() {
        //构建查询pop参数
        TaskQueryParam taskQueryParam = buildPopTaskQueryParam(TaskEnum.CLIENT_PUSH_DOWN.getTaskId(), null);
        // 平台客户拉取
        ApiRPCResult<ResultDto> apiRPCResult = popService.pullDataInfo(taskQueryParam);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("#平台客户下推失败 orgId：{}，taskQueryParam:{}, apiRPCResult：{}", comentCfg.getPopOrgId(), JSONObject.toJSONString(taskQueryParam), JSON.toJSONString(apiRPCResult));
            return;
        }
        if (apiRPCResult.getData() == null) {
            return;
        }
        ResultDto resultDto = JSON.parseObject(JSON.toJSONString(apiRPCResult.getData()), ResultDto.class);
        String dataJson = resultDto.getDataJson();
        //解析平台客户数据
        List<PlatformCustomerDto> customerDtos = JSON.parseArray(dataJson, PlatformCustomerDto.class);
        List<Map<String, Object>> detailDatas = new ArrayList<>(customerDtos.size());
        //转化成海翔客户对象
        for (PlatformCustomerDto platformCustomerDto : customerDtos) {
            log.info("获取到药帮忙客户信息: {}", JSON.toJSONString(platformCustomerDto));
            Map<String, Object> map = new HashMap<>();
            map.put("code", "YBM" + platformCustomerDto.getMerchantId());
            map.put("name", platformCustomerDto.getCustomerName());
            map.put("csflag", 1);
            map.put("alias", platformCustomerDto.getCustomerName());
            map.put("address", platformCustomerDto.getPickAddress());
            map.put("storeaddress", platformCustomerDto.getCustomerRegisterAddress());
            map.put("connectman", platformCustomerDto.getPickName());
            map.put("phone", platformCustomerDto.getPickPhone());
            map.put("accountnumber", StringUtils.isNotBlank(platformCustomerDto.getRegisteredBankAccount()) ? platformCustomerDto.getRegisteredBankAccount() : "");
            map.put("deleted", 4);// 3:待审核状态  4//审核流程中
            //资质信息
            map.put("clientgsp1", JSON.toJSON(helpConvertGsp(platformCustomerDto)));
            //结算客户
            map.put("px_clientauth", JSON.toJSON(helpConvertClient(platformCustomerDto)));
            if (StringUtils.isNotBlank(comentCfg.getCustomerTypeId())) {
                map.put("parent_id", comentCfg.getCustomerTypeId().toString());
            }
            detailDatas.add(map);
            List<Map<String, Object>> maps = ListUtil.toList(map);
            //构建参数
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("accountName", comentCfg.getHxAccountName());
            paramMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
            SfApiConfig apiConfig = SfApiConfig.builder().domainAddress(comentCfg.getDomainAddress()).appId(comentCfg.getHxAppId()).appKey(comentCfg.getHxAppKey()).build();
            SeaFlyResult result = seaflyApi.doPostPlus(comentCfg.getImportClientsUrl(), paramMap, maps, SeaFlyResult.class, apiConfig);
            log.info("海翔客户导入接口信息: {},导入参数: {}", JSON.toJSONString(result), JSON.toJSONString(maps));
            List<CustomerHxErrPo> customerHxErrPos = JSON.parseArray(JSON.toJSONString(result.getData()), CustomerHxErrPo.class);
            if (result == null || (result.getStatus() != 200 && !"-1".equals(customerHxErrPos.get(0).getCid()))) {
                log.warn("平台客户下推异常:orgId:{}, customerName:{}, 海翔接口返回信息 result:{}", comentCfg.getPopOrgId(), platformCustomerDto.getCustomerName(), JSON.toJSONString(result));
                continue;
            } else {  //成功走回调
                SellerCustomerCallBackDto sellerCustomerCallBackDto = new SellerCustomerCallBackDto();
                sellerCustomerCallBackDto.setOrgId(comentCfg.getPopOrgId());
                sellerCustomerCallBackDto.setResult(true);
                sellerCustomerCallBackDto.setNo(platformCustomerDto.getCustomerName());
                sellerCustomerCallBackDto.setId(platformCustomerDto.getId());
                TaskQueryParam taskQueryParam1 = buildPopTaskQueryParam(null, ListUtil.toList(sellerCustomerCallBackDto));
                popService.callbackForCustomerPullTask(taskQueryParam1);
            }

        }


    }

    private Map<String, Object> helpConvertClient(PlatformCustomerDto platformCustomerDto) {
        Map<String, Object> clientAuth = new HashMap<>();
        clientAuth.put("name", platformCustomerDto.getClientName());
        clientAuth.put("call", platformCustomerDto.getPickPhone());
        clientAuth.put("idcard", platformCustomerDto.getClientCardNo());
        clientAuth.put("begindate", DateUtil.today());
        clientAuth.put("enddate", DateUtil.format(platformCustomerDto.getClientExpireDate(), "yyyy-MM-dd"));
        return clientAuth;
    }

    /**
     * @param platformCustomerDto 平台客户信息
     * @return 转换海翔后得资质信息
     */
    private Map<String, Object> helpConvertGsp(PlatformCustomerDto platformCustomerDto) {
        Map<String, Object> toZz = new HashMap<>();
        toZz.put("yyzz", StringUtils.isNotBlank(platformCustomerDto.getBusinessLicenseNumber()) ? platformCustomerDto.getBusinessLicenseNumber() : ""); //营业执照
        toZz.put("swdjz", StringUtils.isNotBlank(platformCustomerDto.getBusinessLicenseNumber()) ? platformCustomerDto.getBusinessLicenseNumber() : ""); //税务登记号
        toZz.put("xkzh", StringUtils.isNotBlank(platformCustomerDto.getPermitNumber()) ? platformCustomerDto.getPermitNumber() : ""); //许可证号
        if (!ObjectUtils.isEmpty(platformCustomerDto.getPermitExpireDate())) {
            toZz.put("xkzyxq", DateFormatUtils.format(platformCustomerDto.getPermitExpireDate(), "yyyy-MM-dd"));
        } else {
            toZz.put("xkzyxq", "1970-01-01");
        }//许可证有效期
        if (StringUtils.isNotBlank(platformCustomerDto.getClientName())) {
            toZz.put("swtr", platformCustomerDto.getClientName());
        } else {
            toZz.put("swtr", "");
        }//委托人
        toZz.put("qyfzr", platformCustomerDto.getLegalPerson());
        if (StringUtils.isNotBlank(platformCustomerDto.getClientCardNo())) {
            toZz.put("sfz", platformCustomerDto.getClientCardNo());
        } else {
            toZz.put("sfz", "");
        }//身份证
        if (!ObjectUtils.isEmpty(platformCustomerDto.getClientCardExpireDate())) {
            toZz.put("sfzvaliddate", DateFormatUtils.format(platformCustomerDto.getClientCardExpireDate(), "yyyy-MM-dd"));
        } else {
            toZz.put("sfzvaliddate", "1970-01-01");
        } //身份证有效期

        if (!ObjectUtils.isEmpty(platformCustomerDto.getClientExpireDate())) {
            toZz.put("stsyxq", DateFormatUtils.format(platformCustomerDto.getClientExpireDate(), "yyyy-MM-dd"));
        } else {
            toZz.put("stsyxq", "1970-01-01");
        }//委托书有效期
        toZz.put("frdb", platformCustomerDto.getLegalPerson());
        toZz.put("stdqdw", platformCustomerDto.getProvinceName()); //受委托地区
        toZz.put("ylqxjybapz", platformCustomerDto.getClassIIMedicalDeviceNo());
        toZz.put("yyzzyxq", DateUtil.format(platformCustomerDto.getBusinessLicenseExpireDate(), "yyyy-MM-dd"));
        return toZz;
    }

    /**
     * 出库明细同步
     */
    @Override
    public void syncOrderStatePop() {
        TaskQueryParam taskQueryParam = buildPopTaskQueryParam(TaskEnum.ORDER_DELIVERY_DETAILE.getTaskId(), null);
        //从POP平台查询需要出库得订单号
        ApiRPCResult<ResultDto> apiRPCResult = popService.queryTaskCondition(taskQueryParam);
        if (apiRPCResult == null || apiRPCResult.isFail()) {
            log.warn("PopErpTaskServiceImpl.syncOrderStatePop#查询待配送同步条件失败 orgId：{}，apiRPCResult：{}", comentCfg.getPopOrgId(), JSON.toJSONString(apiRPCResult));
        }
        if (apiRPCResult.getData() == null) {
            log.warn("PopErpTaskHXServiceImpl.syncOrderStatePop#没有可同步的待配送订单 orgId：{}，apiRPCResult：{}", comentCfg.getPopOrgId(), JSON.toJSONString(apiRPCResult));
            return;
        }
        ResultDto resultDto = JSON.parseObject(JSON.toJSONString(apiRPCResult.getData()), ResultDto.class);
        TaskConditionDto taskConditionDto = JSON.parseObject(resultDto.getDataJson(), TaskConditionDto.class);
        //要要配送的订单号
        List<String> listQueryParam = taskConditionDto.getListQueryParam();
        SfApiConfig apiConfig = SfApiConfig.builder().domainAddress(comentCfg.getDomainAddress()).appId(comentCfg.getHxAppId()).appKey(comentCfg.getHxAppKey()).build();
        List<SellerOrderDeliverDetailForErpDto> orderDeliverDetailForErpDtoList = new ArrayList<>();
        for (String orderNo : listQueryParam) {
            orderDeliverDetailForErpDtoList.addAll(getHxOrderInfo(orderNo, apiConfig));
        }
        if (CollectionUtils.isEmpty(orderDeliverDetailForErpDtoList)) {
            log.info("库库订单信息为查w到请检询数据!!!");
            return;
        }
        //构建POP请求参数
        TaskQueryParam taskQueryParam1 = buildPopTaskQueryParam(TaskEnum.ORDER_DELIVERY_DETAILE.getTaskId(), orderDeliverDetailForErpDtoList);
        //出库信息回传
        ApiRPCResult<Boolean> apiRPCResult1 = popService.pushDataInfo(taskQueryParam1);
        if (apiRPCResult1 == null || apiRPCResult1.isFail() || !apiRPCResult1.getData()) {
            log.warn("PopErpTaskHXServiceImpl.syncOrderStatePop#任务上报失败 accountName:{}, apiRPCResult：{}", comentCfg.getHxAccountName(), JSON.toJSONString(apiRPCResult));
            return;
        } else {
            log.info("出库信息上报成功{}条 当前时间: {}", orderDeliverDetailForErpDtoList.size(), DateUtil.now());
        }


    }

    private List<SellerOrderDeliverDetailForErpDto> getHxOrderInfo(String orderNo, SfApiConfig apiConfig) {
        Map<String, Object> paramMap = buildOrderParam(orderNo);
        //调用海翔http接口查询库存信息
        SeaFlyResult<OrderStatusHxPo> result = seaflyApi.doPostPlus(comentCfg.getGetSaleBillInfo(), paramMap, SeaFlyResult.class, apiConfig);
        if (result == null || result.getStatus() != 200) {
            log.warn("#getSaleBillInfo.api 接口返回状态异常, result：{} 当前订单未查询到海翔出库单: {}", JSON.toJSONString(result), orderNo);
            return new ArrayList<>();
        }
        log.info("出库信息查询成功:{}", JSON.toJSONString(result.getData()));
        List<OrderStatusHxPo> orderStatusHxPos = JSON.parseArray(JSON.toJSONString(result.getData()), OrderStatusHxPo.class);
        if (orderStatusHxPos == null || CollectionUtils.isEmpty(orderStatusHxPos)) {
            log.warn("#getSaleBillInfo.api 接口返回数量为空 result：{},未查询到出库单:{}", JSON.toJSONString(orderStatusHxPos), orderNo);
            return new ArrayList<>();
        }
        return convertToPopOrderDetail(orderStatusHxPos.get(0));
    }

    private List<SellerOrderDeliverDetailForErpDto> convertToPopOrderDetail(OrderStatusHxPo orderStatusHxPo) {
        List<SellerOrderDeliverDetailForErpDto> orderList = new ArrayList<>();
        BillHead billhead = orderStatusHxPo.getBillhead();
        if ("0".equals(billhead.getBillstate())) {
            List<BillDetail> billdetail = orderStatusHxPo.getBilldetail();
            for (BillDetail billDetail : billdetail) {
                SellerOrderDeliverDetailForErpDto orderDetail = new SellerOrderDeliverDetailForErpDto();
                orderDetail.setOrderNo(billDetail.getRefbillnumber());
                orderDetail.setOrderDetailId(Long.valueOf(billDetail.getRemark()));
                orderDetail.setErpCode(billDetail.getCode());
                orderDetail.setProductName(billDetail.getName());
                orderDetail.setBatchCode(billDetail.getBatchcode());
                orderDetail.setBatchNumDecimal(BigDecimal.valueOf(billDetail.getQty()));
                orderDetail.setBatchValidDate(billDetail.getValiddate().substring(0, 10));
                orderDetail.setProductionDate(billDetail.getProductdate().substring(0, 10));
                orderDetail.setBatchPrice(BigDecimal.valueOf(billDetail.getPrice()));
                orderList.add(orderDetail);
            }
        }
        return orderList;
    }

    private <T> TaskQueryParam buildPopTaskQueryParam(Integer taskId, List<T> list) {
        TaskQueryParam taskQueryParam = new TaskQueryParam();
        taskQueryParam.setOrgId(comentCfg.getPopOrgId());
        taskQueryParam.setAppId(comentCfg.getPopAppId());
        if (taskId != null) {
            taskQueryParam.setTaskId(taskId);
        }
        if (!CollectionUtils.isEmpty(list)) {
            taskQueryParam.setJsonData(JSON.toJSONString(list));
        }
        Map<String, Object> popParamMap = JSON.parseObject(JSON.toJSONString(taskQueryParam)).getInnerMap();
        taskQueryParam.setSign(MD5Util.encrypt(popParamMap, comentCfg.getPopAppSecret()));
        return taskQueryParam;
    }

    private Map<String, Object> buildOrderParam(String orderNo) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("accountName", comentCfg.getHxAccountName());
        paramMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
        paramMap.put("billnumbers", orderNo + ";");
        //paramMap.put("begindate", DateUtils.format(DateUtils.getBeginDayOfYear()));
        paramMap.put("begindate", "2025-01-01");
        paramMap.put("enddate", DateUtil.format(new Date(), "yyyy-MM-dd"));
        paramMap.put("page", "1");
        paramMap.put("rows", "100");
        return paramMap;
    }

}
